package com.doucat.support.http;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * -----------------------------------------------------------------
 * Copyright (C) 2021-2031, by tonly, All rights reserved.
 * -----------------------------------------------------------------
 * File: Client.java
 * Author: wangfy
 * Create: 2021/5/24 16:04
 */
public class BaseClient {
//    public static final String BASE_URL = "http://10.68.70.43:8282/";
    private String BASE_URL = "http://cloud.sntonly.com/";
    private Retrofit retrofit;
    public BaseClient(String BASE_URL) {
        this.BASE_URL=BASE_URL;
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.cookieJar(new CookieJar() {
            //这里一定一定一定是HashMap<String, List<Cookie>>,是String,不是url.
            private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

            @Override
            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                cookieStore.put(url.host(), cookies);
            }

            @Override
            public List<Cookie> loadForRequest(HttpUrl url) {
                List<Cookie> cookies = cookieStore.get(url.host());
                return cookies != null ? cookies : new ArrayList<Cookie>();
            }
        });
        builder.readTimeout(60*1000, TimeUnit.MILLISECONDS);      //全局的读取超时时间
        builder.writeTimeout(20*1000, TimeUnit.MILLISECONDS);     //全局的写入超时时间
        builder.connectTimeout(20*1000, TimeUnit.MILLISECONDS);   //全局的连接超时时间
        OkHttpClient client = builder.build();
        retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(initGson()))
                .baseUrl(BASE_URL)
                .client(client)
                .build();
    }
    private Gson initGson() {
        return new GsonBuilder()
                .create();
    }

    public Retrofit getRetrofit() {
        return retrofit;
    }
}